package zhou.chs.p9_2;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    TextView tv1, tv2, tv3, tv4;  //显示读取到的寄存器值
    EditText et1, et2, et3, et4;  //编辑写入寄存器的值
    Button btwrite;  //写入PLC数据按钮
    private Handler mHandler; 		//消息线程
    private Socket mSocket;        //TCP_Client Socket
    private StartThread st;            //TCP客户端线程
    private ConnectedThread rt;    //TCP数据交换线程
    private byte rbuf[] = new byte[512];    //接收数据
    boolean running = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv1 = (TextView) findViewById(R.id.idtv1);   //实例化控件
        tv2 = (TextView) findViewById(R.id.idtv2);
        tv3 = (TextView) findViewById(R.id.idtv3);
        tv4 = (TextView) findViewById(R.id.idtv4);
        et1 = (EditText) findViewById(R.id.idet1);
        et2 = (EditText) findViewById(R.id.idet2);
        et3 = (EditText) findViewById(R.id.idet3);
        et4 = (EditText) findViewById(R.id.idet4);
        btwrite=(Button) findViewById(R.id.button);
        btwrite.setEnabled(false);
        mHandler = new MyHandler();		//实例化Handler，用于进程间的通信
        st = new StartThread();
        st.start(); //连接服务器
    }
    // 按钮响应程序
    public void wr(View view){
        byte[] buf =new byte[4];
        String s = et1.getText().toString();
        buf[0] = (byte) (Integer.parseInt(s)&0xFF);
        s = et2.getText().toString();
        buf[1] = (byte) (Integer.parseInt(s)&0xFF);
        s = et3.getText().toString();
        buf[2] = (byte) (Integer.parseInt(s)&0xFF);
        s = et4.getText().toString();
        buf[3] = (byte) (Integer.parseInt(s)&0xFF);
        rt.write(buf);  //向PLC发送数据
    }
    //建立socket连接的线程
    private class StartThread extends Thread {
        @Override
        public void run() {
            try {
                mSocket = new Socket("192.168.2.1", 3000);//连接PLC
                //启动接收数据的线程
                rt = new ConnectedThread(mSocket);
                rt.start();
                running = true;
                if (mSocket.isConnected()) {  //成功连接获取socket对象则发送成功消息
                    Message msg = mHandler.obtainMessage();
                    msg.what = 0;
                    mHandler.sendMessage(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //数据输入输出线程
    private class ConnectedThread extends Thread {
        private final Socket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        public ConnectedThread(Socket socket) {   //socket连接
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                tmpIn = mmSocket.getInputStream();      //数据通道创建
                tmpOut = mmSocket.getOutputStream();
            } catch (IOException e) {
            }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
        public final void run() {
            while (running) {
                int byt;
                try {
                    byt = mmInStream.read(rbuf);     // 监听接收到的数据
                    if (byt > 0) {
                        Message msg1 = mHandler.obtainMessage();
                        msg1.what = 1;
                        msg1.obj = byt;
                        mHandler.sendMessage(msg1); // 通知主线程接收到数据
                        try {
                            sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (NullPointerException e) {
                    running = false;
                    Message msg2 = mHandler.obtainMessage();
                    msg2.what = 2;
                    mHandler.sendMessage(msg2);
                    e.printStackTrace();
                    break;
                } catch (IOException e) {
                    break;
                }
            }
        }
        public void write(byte[] bytes) {       //发送字节数据
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
            }
        }
        public void cancel() {      //关闭连接
            try {
                mmSocket.close();
            } catch (IOException e) {
            }
        }
    }
    //在主线程处理Handler传回来的message
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0: // 已连接网络
                    btwrite.setEnabled(true);
                    break;
                case 1: // 收到数据
                    int n=Integer.parseInt(msg.obj.toString());
                    if(n==4){  //收到读取数据
                        tv1.setText(String.format("%d", rbuf[0]));
                        tv2.setText(String.format("%d", rbuf[1]));
                        tv3.setText(String.format("%d", rbuf[2]));
                        tv4.setText(String.format("%d", rbuf[3]));
                    }
                    break;
                case 2: // 网络中断
                    btwrite.setEnabled(false);
                    break;
            }
        }
    }
}